package com.autumn.aitraffic.controller;

import com.autumn.aitraffic.api.Result;
import com.autumn.aitraffic.domain.po.*;
import com.autumn.aitraffic.domain.vo.HomePageVo;
import com.autumn.aitraffic.service.impl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.DayOfWeek;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/homepage")
public class HomeController {
    @Autowired
    private VehicleServiceImpl vehicleService;
    
    @Autowired
    private CarListServiceImpl carListService;
    
    @Autowired
    private CongestionServiceImpl congestionService;
    
    @Autowired
    private JitteralarmServiceImpl jitteralarmService;
    
    @Autowired
    private SpeedingServiceImpl speedingService;
    
    @Autowired
    private RunRedLightServiceImpl runRedLightService;
    
    @Autowired
    private ReverseServiceImpl reverseService;
    
    @Autowired
    private PassLineServiceImpl passLineService;
    
    @Autowired
    private NoComityServiceImpl noComityService;
    
    @Autowired
    private IllegalTrackServiceImpl illegalTrackService;
    
    @Autowired
    private BackOffServiceImpl backOffService;
    
    @GetMapping
    public Result homepage(int time) {
        // 创建返回对象
        HomePageVo homePageVo = new HomePageVo();
        
        // 设置固定日期范围，基于2025年
        LocalDateTime startTime;
        LocalDateTime endTime;
        
        // 设置固定的结束时间为2025年4月30日
        LocalDate endDate = LocalDate.of(2025, Month.APRIL, 30);
        endTime = endDate.atTime(LocalTime.MAX);
        
        switch (time) {
            case 0: // 4月最后一周
                // 获取4月最后一周的开始日期（30号往前推7天）
                LocalDate lastWeekStart = endDate.minusDays(6);
                startTime = lastWeekStart.atStartOfDay();
                break;
            case 1: // 整个4月
                // 获取4月第一天
                LocalDate aprilStart = LocalDate.of(2025, Month.APRIL, 1);
                startTime = aprilStart.atStartOfDay();
                break;
            case 2: // 3月+4月
                // 获取3月第一天
                LocalDate marchStart = LocalDate.of(2025, Month.MARCH, 1);
                startTime = marchStart.atStartOfDay();
                break;
            case 3: // 2025年1~4月
                // 获取1月第一天
                LocalDate yearStart = LocalDate.of(2025, Month.JANUARY, 1);
                startTime = yearStart.atStartOfDay();
                break;
            default: // 默认为4月最后一周
                LocalDate defaultWeekStart = endDate.minusDays(6);
                startTime = defaultWeekStart.atStartOfDay();
                break;
        }
        
        // 计算特殊车辆类型（4和6）和非特殊车辆的数量 - 查询所有路口
        List<CarList> allVehicles = carListService.lambdaQuery()
                .between(CarList::getVioTime, startTime, endTime)
                .list();
                
        List<CarList> specialVehicles = allVehicles.stream()
                .filter(v -> v.getCarType() == 4 || v.getCarType() == 6)
                .collect(Collectors.toList());
        
        // 最后一天的车辆（2025年4月30日）
        LocalDateTime lastDayStart = endDate.atStartOfDay();
        LocalDateTime lastDayEnd = endDate.atTime(LocalTime.MAX);
        
        List<CarList> lastDayVehicles = allVehicles.stream()
                .filter(v -> v.getVioTime().isAfter(lastDayStart) && v.getVioTime().isBefore(lastDayEnd))
                .collect(Collectors.toList());
                
        List<CarList> lastDaySpecialVehicles = lastDayVehicles.stream()
                .filter(v -> v.getCarType() == 4 || v.getCarType() == 6)
                .collect(Collectors.toList());
        
        // 获取拥堵信息 - 查询所有路口
        List<Congestion> congestionList = congestionService.lambdaQuery()
                .between(Congestion::getStartTime, startTime, endTime)
                .list();
                
        // 检查是否有任何路口当前处于拥堵状态
        boolean isBlock = congestionService.lambdaQuery()
                .isNull(Congestion::getEndTime)
                .count() > 0;
        
        // 获取摄像头偏移信息 - 查询所有路口
        boolean isAlarm = jitteralarmService.lambdaQuery()
                .eq(Jitteralarm::getAlarm, true)
                .count() > 0;
        
        // 获取事故信息 - 新规则: 当time==2或3时，accident=true
        boolean isAccident = (time == 2 || time == 3);
        
        // 统计违规数据 - 从car_list表中获取
        int type1Count = (int) allVehicles.stream()
                .filter(v -> v.getVioCause() == 1)  // 闯红灯
                .count();
                
        int type2Count = (int) allVehicles.stream()
                .filter(v -> v.getVioCause() == 2)  // 未礼让行人
                .count();
                
        int type3Count = (int) allVehicles.stream()
                .filter(v -> v.getVioCause() == 3)  // 超速
                .count();
                
        int type4Count = (int) allVehicles.stream()
                .filter(v -> v.getVioCause() == 4)  // 未按规定路径行驶
                .count();
        
        // 所有违规数量
        int totalViolations = type1Count + type2Count + type3Count + type4Count;
        
        // 填充 groupData
        HomePageVo.GroupData groupData = new HomePageVo.GroupData();
        groupData.setAlarm(isAlarm);
        groupData.setBlock(isBlock);
        groupData.setAccident(isAccident);
        groupData.setViolation(totalViolations);
        groupData.setSpecNum(specialVehicles.size());
        groupData.setTraffic(allVehicles.size());
        homePageVo.setGroupData(groupData);
        
        // 填充 todayCarNum - 修改为当前时间段内的特殊车辆和非特殊车辆数量
        List<Integer> periodCarNum = new ArrayList<>();
        periodCarNum.add(specialVehicles.size()); // 特殊车辆数
        periodCarNum.add(allVehicles.size() - specialVehicles.size()); // 非特殊车辆数
        homePageVo.setTodayCarNum(periodCarNum);
        
        // 填充 carNumList（按7种车型统计）
        List<Integer> carNumList = new ArrayList<>();
        // 统计车辆类型 1-小轿车,2-公交车, 3-面包车, 4-油罐车, 5-集装箱车, 6-工程车, 7-小型卡车
        for (int i = 1; i <= 7; i++) {
            final int carType = i;
            int count = (int) allVehicles.stream()
                    .filter(v -> v.getCarType() == carType)
                    .count();
            carNumList.add(count);
        }
        
        homePageVo.setCarNumList(carNumList);
        
        // 填充 weekNum - 固定为4月最后7天的数据
        List<Integer> timeSeriesData = new ArrayList<>();
        
        // 获取4月的最后一天
        LocalDate april = LocalDate.of(2025, Month.APRIL, 1);
        LocalDate lastDayOfApril = april.with(TemporalAdjusters.lastDayOfMonth());
        
        // 获取4月最后7天（从周四到周三）
        LocalDate lastWeekThursday = lastDayOfApril.minusDays(6); // 从最后一天往前推6天得到周四
        
        // 数据重新排序为周一到周日
        LocalDate monday = lastWeekThursday.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
        
        // 查询并统计4月最后一周每天的车辆数量，按周一到周日排序
        for (int i = 0; i < 7; i++) {
            LocalDate currentDate = monday.plusDays(i);
            LocalDateTime dayStart = currentDate.atStartOfDay();
            LocalDateTime dayEnd = currentDate.atTime(LocalTime.MAX);
            
            // 如果日期在4月最后7天内，则查询实际数据，否则使用默认值
            if (currentDate.isAfter(lastWeekThursday.minusDays(1)) && 
                currentDate.isBefore(lastWeekThursday.plusDays(7))) {
                
                int dailyTraffic = (int) allVehicles.stream()
                    .filter(v -> v.getVioTime().isAfter(dayStart) && v.getVioTime().isBefore(dayEnd))
                    .count();
                
                timeSeriesData.add(dailyTraffic);
            } else {
                // 对于超出4月的日期，添加模拟数据
                timeSeriesData.add(10 + i * 2); // 模拟数据，从10开始每天增加2
            }
        }
        
        homePageVo.setWeekNum(timeSeriesData);
        
        // 填充 roadSit
        List<HomePageVo.RoadSitVo> roadSitList = new ArrayList<>();
        
        // 从数据库获取所有活跃的路口ID
        List<Integer> intersections = carListService.lambdaQuery()
                .between(CarList::getVioTime, startTime, endTime)
                .select(CarList::getIntersection)  // 只选择intersection列
                .groupBy(CarList::getIntersection) // 按intersection分组
                .list()
                .stream()
                .map(CarList::getIntersection)
                .collect(Collectors.toList());

        // 如果没有数据，至少展示5个路口
        if (intersections.isEmpty()) {
            for (int i = 1; i <= 5; i++) {
                intersections.add(i);
            }
        }

        // 对每个路口进行数据统计
        for (Integer intersection : intersections) {
            HomePageVo.RoadSitVo roadSitVo = new HomePageVo.RoadSitVo();
            roadSitVo.setRoadName(intersection + "号路口");
            
            // 查询该路口的车辆总数
            long roadCarNum = carListService.lambdaQuery()
                    .eq(CarList::getIntersection, intersection)
                    .between(CarList::getVioTime, startTime, endTime)
                    .count();
                    
            // 查询该路口的特殊车辆数
            long roadSpecNum = carListService.lambdaQuery()
                    .eq(CarList::getIntersection, intersection)
                    .in(CarList::getCarType, 4, 6)
                    .between(CarList::getVioTime, startTime, endTime)
                    .count();
            
            // 统计该路口的违法车辆数量        
            int roadVioNum = (int) carListService.lambdaQuery()
                    .eq(CarList::getIntersection, intersection)
                    .ne(CarList::getVioCause, 0) // 0表示正常，其他表示违法
                    .between(CarList::getVioTime, startTime, endTime)
                    .count();
            
            // 摄像头偏移状态
            boolean roadIsAlarm = jitteralarmService.lambdaQuery()
                    .eq(Jitteralarm::getIntersection, intersection)
                    .eq(Jitteralarm::getAlarm, true)
                    .count() > 0;
                    
            // 拥堵状态
            boolean roadIsBlock = congestionService.lambdaQuery()
                    .eq(Congestion::getIntersection, intersection)
                    .isNull(Congestion::getEndTime)
                    .count() > 0;
                    
            // 事故状态 - 当是4号路口且time为2或3时设置为true
            boolean roadIsAccident = (intersection == 4) && (time == 2 || time == 3);
            
            roadSitVo.setCarNum((int) roadCarNum);
            roadSitVo.setSpecNum((int) roadSpecNum);
            roadSitVo.setVioNum(roadVioNum);
            roadSitVo.setAlarm(roadIsAlarm);
            roadSitVo.setIsblock(roadIsBlock);
            roadSitVo.setStatus(0); // 默认状态
            roadSitVo.setAccident(roadIsAccident);
            
            roadSitList.add(roadSitVo);
        }
        homePageVo.setRoadSit(roadSitList);
        
        // 填充 blockNum - 固定为星期一到星期天的拥堵次数[1,2,2,3,2,0,0]
        List<Integer> blockNum = Arrays.asList(1, 2, 2, 3, 2, 0, 0);
        homePageVo.setBlockNum(blockNum);
        
        // 统计违规类型的数量 (type1: 闯红灯, type2: 未礼让行人, type3: 超速, type4: 未按规定路径行驶)
        List<Integer> vioNum = new ArrayList<>();
        vioNum.add(type1Count);
        vioNum.add(type2Count);
        vioNum.add(type3Count);
        vioNum.add(type4Count);
        homePageVo.setVioNum(vioNum);
        
        return Result.succ(null, homePageVo);
    }
}
